﻿using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using QW.Core.Domain;
using QW.Core.Web;
using QW.Found.JwtAuthorize;

namespace QW.Found.Extensions
{
    /// <summary>
    /// 系统内核扩展
    /// </summary>
    public static class CoreExtensions
    {
        /// <summary>
        /// 引入系统基础内核
        /// </summary>
        /// <param name="services"></param>
        /// <param name="option">启动配置</param>
        /// <param name="serviceBuilder">自定义的服务</param>
        public static IServiceCollection AddSystemCore(this IServiceCollection services, CoreStartupOption option)
        {
            //GB2312 编码支持
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            //静态上下文
            services.AddHttpContextAccessor();

            //由于webapi使用的时分布式缓存机制存放session，放弃session的使用
            //mvc下可以自己手动添加
            //services.AddSession();
            //方法1:使用内存
            //services.AddDistributedMemoryCache();
            //方法2:使用redis
            //RedisHelper.Initialization(new CSRedisClient("连接字符串"));
            //services.AddSingleton<IDistributedCache>(new CSRedisDistributedCache(RedisHelper.Instance));

            //注入依赖
            services.AddDependencyInjection(option.ProjectAssemblies);

            //注册 AutoMapper
            services.AddAutoMapper(option.ProjectAssemblies);

            #region 跨域
            if (option.CorsOption != null && !string.IsNullOrWhiteSpace(option.CorsOption.PolicyName))
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(option.CorsOption.PolicyName, policy => policy.WithOrigins(option.CorsOption.Origins.Split(','))
                    .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
                    .AllowAnyHeader()
                    );
                });
            }
            #endregion

            #region JWT
            services.AddApiJwtAuthorize(option.JwtConfig, option.PermissionAction);
            #endregion

            #region 支持同步读流
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
            .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
            #endregion

            return services;
        }
        /// <summary>
        /// 启用系统基础内核
        /// </summary>
        /// <param name="app"></param>
        /// <param name="option"></param>
        public static IApplicationBuilder UseSystemCore(this IApplicationBuilder app, CoreStartupOption option)
        {
            //使用Session
            app.UseSession();

            //使用静态上下文
            app.UseStaticHttpContext();

            //公共静态上下文
            GlobalContext.SetContextContent(app.ApplicationServices);

            #region 跨域相关
            if (option.CorsOption != null && !string.IsNullOrWhiteSpace(option.CorsOption.PolicyName))
            {
                app.UseCors(option.CorsOption.PolicyName);
            }
            #endregion

            return app;
        }
    }
}
